package com.fqgame.user.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * 异步任务服务
 */
@Service
public class AsyncTaskService {

    private static final Logger logger = LoggerFactory.getLogger(AsyncTaskService.class);

    /**
     * 异步执行任务，使用commonThreadPool线程池
     * @param taskName 任务名称
     */
    @Async("commonThreadPool")
    public void executeAsyncTask(String taskName) {
        logger.info("开始执行异步任务: {}", taskName);
        try {
            // 模拟耗时操作
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("异步任务执行中断: {}", taskName, e);
        }
        logger.info("异步任务执行完成: {}", taskName);
    }

    /**
     * 异步执行IO密集型任务，使用ioThreadPool线程池
     * @param fileName 文件名
     * @return CompletableFuture<String>
     */
    @Async("ioThreadPool")
    public CompletableFuture<String> processFileAsync(String fileName) {
        logger.info("开始处理文件: {}", fileName);
        try {
            // 模拟文件处理
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("文件处理中断: {}", fileName, e);
            return CompletableFuture.failedFuture(e);
        }
        String result = "文件 " + fileName + " 处理完成";
        logger.info(result);
        return CompletableFuture.completedFuture(result);
    }

    /**
     * 执行计算密集型任务
     * @param data 数据
     * @return 处理结果
     */
    public String processData(String data) {
        logger.info("开始处理数据: {}", data);
        // 模拟复杂计算
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            result.append(data).append(i);
        }
        logger.info("数据处理完成: {}", data);
        return result.toString();
    }
}